package at.bherbst.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketTimeoutException;

import android.util.Log;

public class ForwarderRunnable implements Runnable {

	private static final String TAG = "ForwarderRunnable";
	private int port_dest;
	private int port_incoming;
	private int port_outgoing;
	String text;
	private InetAddress serverip;
	private InetAddress serverip_incoming;

	/**
	 * this is needed to bind the sending socket to the right IP
	 */
	private InetAddress serverip_outgoing;

	DatagramSocket incomingSocket = null;
	DatagramSocket outgoingSocket = null;

	ForwarderRunnable(String serverip, String serverip_incoming) {
		this.port_dest = 1500;
		this.port_incoming = 1501;
		this.port_outgoing = 1502;
		try {
			this.serverip = InetAddress.getByName(serverip);
			this.serverip_incoming = InetAddress.getByName(serverip_incoming);
			this.serverip_outgoing = InetAddress.getByName("192.168.43.1");
		} catch (Exception e) {
			Log.e(TAG, e.getMessage(), e);
			e.printStackTrace();
		}
	}

	public void run() {
		Log.d(TAG, "Starting in run() ...");
		try {
			byte[] message = new byte[1500];
			DatagramSocket incomingSocket = new DatagramSocket(
					new InetSocketAddress(serverip_incoming, port_incoming));
			incomingSocket.setSoTimeout(2000);
			Log.d(TAG, "incomingSocket created");
			DatagramSocket outgoingSocket = new DatagramSocket(
					new InetSocketAddress(serverip_outgoing, port_outgoing));
			Log.d(TAG, "outgoingSocket created, going into while");
			while (!Thread.interrupted() && incomingSocket != null
					&& outgoingSocket != null) {
				Log.d(TAG, "creating Packet");
				DatagramPacket p = new DatagramPacket(message, message.length);
				Log.d(TAG, "waiting for message ...");
				try {
					incomingSocket.receive(p);
					text = new String(message, 0, p.getLength());
					Log.d(TAG, "message:" + text);
					int msg_length = text.length();
					byte[] message2 = text.getBytes();
					DatagramPacket pTo = new DatagramPacket(message2,
							msg_length, serverip, port_dest);
					Log.d(TAG, "Sending message: " + text + " to " + serverip
							+ ":" + port_dest);
					outgoingSocket.send(pTo);
					Log.d(TAG, "\tsent");
				} catch (SocketTimeoutException e) {
					Log.d(TAG, e.getMessage() + ", starting over ...");
				}
			}
			incomingSocket.close();
			outgoingSocket.close();
			Log.d(TAG, "interrupted --> leaving while");
		} catch (IOException e) {
			Log.e(TAG, e.getMessage(), e);
			e.printStackTrace();
		}
	}

}
